import Dialog from "../../component/vant/dialog/dialog";
import Toast from "../../component/vant/toast/toast";
const qiniuUploader = require("../../utils/qiniuUploader.js");
const util = require("../../utils/util.js");
var WxParse = require('../../component/wxParse/wxParse.js');
var app = getApp();
const select_options = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    downloadUrl: app.api.xh.downloadDomain,//下载文件域名
    question_html: app.api.xh.domain,//题干请求域名
    questionCount: 0,
    sections: [],
    if_commit: 2,
    select_options: select_options,
    setInter: '',
    num: 0,
    doneQCount: 0,
    show_status: false,
    files: [],
    picture_list: [],
    file_list: [],
    check_mode: 0,//自批模式
    coach_answer: {},
    video_list: [],
    showSkeleton: true
  },
  submit: function () {
    var page = this,
        item_list = [],
        sections = page.data.sections;

    var check_done = 1;//判断是否完成所有客观题作答
    var item_list = [];
    var objective_score = 0;//客观题分数
    var has_subjective_question = 1;
    sections.map((item, index) => {
      if (item.category == 'select' || item.category == 'judge') {
        sections[index].questions.map((q, i) => {
          if (sections[index].questions[i].student_answer == undefined) {
            check_done = 0;
          } else {
            //多选题的情况
            var if_right = 2;
            var student_answer = sections[index].questions[i].student_answer;
            var correct = sections[index].questions[i].correct;
            if (sections[index].questions[i].correct.length > 1) {
              student_answer = student_answer.join('');
              if (student_answer.sort().toString() == correct.sort().toString()) {
                if_right = 1;
              }
            }
            item_list.push({
              uuid: sections[index].questions[i].uuid,
              answer: sections[index].questions[i].student_answer,
              if_right: if_right
            })
            objective_score += if_right == 1 ? sections[index].questions[i].score * 1 : 0;
          }
        })
      }
    });


    //判断是否有主观题
    // 客观题数量
    var objective_question_num = 0;
    sections.map((item, index) => {
      sections[index].questions.map((question, i) => {
        if (question.category == 'select' || question.category == 'judge') {
          objective_question_num += 1;
        }
      })
    });

    // 是否含有主观题
    if (objective_question_num == page.data.questionCount) {
      has_subjective_question = 0;
    } else {
      has_subjective_question = 1;
    }
    //判断是否有主观题


    if (check_done == 0) {
      Dialog.alert({
        message: '请先完成所有客观题的作答。'
      }).then(() => {
        return false;
      });
    }

    var answer_json = {
      finish: !has_subjective_question,
      picture_list: page.data.picture_list,
      score: objective_score,
      use_time: page.data.timeCounter,
      item_list: item_list
    };

    var param = {
      answer_json: JSON.stringify(answer_json)
    }

    Toast('提交成功！');
    app.setPageTitle('自批主观题');
    page.setData({
      check_mode: 1
    })

  },
  //html转wxml处理
  processHtml: function (){
    var page = this;
    var sections = page.data.sections;
    var stemArr = [];
    var analysisArr = [];

    //获取题干解析html总请求数
    var body_url_cnt = 0, body_url_load_cnt = 0;
    var analysis_url_cnt = 0, analysis_url_load_cnt = 0;
    sections.map((s) => {
      s.questions.map((q) => {
        if (q.bodyUrl != undefined && q.bodyUrl.length > 0) {
          body_url_cnt++;
        }
        if (q.analysisUrl != undefined && q.analysisUrl.length > 0) {
          analysis_url_cnt++;
        }
      })
    })

    sections.map((item,i) => {
      item.questions.map((q,k) => {

        //获取题干&解析的html内容
        if (q.bodyUrl != undefined && q.bodyUrl.length > 0) {
          util.get(page.data.question_html + '/' + q.bodyUrl).then(function (res) {
            body_url_load_cnt++;
            sections[i].questions[k].body = res.data.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
            if (body_url_load_cnt == body_url_cnt) {
              page.setData({
                sections: sections
              })
            }
          })
        } else {
          sections[i].questions[k].body = q.body.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
        }
        if (q.analysisUrl != undefined && q.analysisUrl.length > 0) {
          util.get(page.data.question_html + '/' + q.analysisUrl).then(function (res) {
            analysis_url_load_cnt++;
            sections[i].questions[k].analysis = res.data.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
            if (analysis_url_load_cnt == analysis_url_cnt) {
              page.setData({
                sections: sections
              })
            }
          })
        } else {
          sections[i].questions[k].analysis = q.analysis.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
        }
        //获取题干&解析的html内容

        //-----题干、解析html转wxml-----
        /*if (q.body.length > 0) {
          stemArr[q.order - 1] = q.body;
        } else {
          util.get(page.data.downloadUrl + '/' + q.bodyUrl).then(function (res) {
            body_url_load_cnt++;
            stemArr[q.order - 1] = res.data;
          })
        }

        if (q.analysis.length > 0) {
          analysisArr[q.order - 1] = q.analysis;
        } else {
          util.get(page.data.downloadUrl + '/' + q.analysisUrl).then(function (res) {
            analysis_url_load_cnt++;
            analysisArr[q.order - 1] = res.data;
          })
        }

        WxParse.wxParse('stem' + (q.order - 1), 'html', stemArr[(q.order - 1)], page);
        WxParse.wxParse('analysis' + (q.order - 1), 'html', analysisArr[(q.order - 1)], page);

        if (body_url_load_cnt == body_url_cnt) {
          WxParse.wxParseTemArray("stemTemArray", 'stem', stemArr.length, page);
        }
        if (analysis_url_load_cnt == analysis_url_cnt) {
          WxParse.wxParseTemArray("analysisTemArray", 'analysis', analysisArr.length, page);
        }*/
        //-----题干、解析html转wxml-----
      })
    });
    page.setData({
      sections: sections
    })
  },
  toVideoDetail: function (e) {
    var video_id = e.currentTarget.dataset.id;
    var video_url = e.currentTarget.dataset.url;
    // wx.navigateTo({
    //   url: '../video_preview/video_preview?video_id=' + video_id + '&video_url=' + video_url,
    // })
    wx.navigateTo({
      url: '/pages/preview/preview?type=video&file_url=' + video_url + '&name=讲解'
    });

  },
  //去自批
  toCheckSelf: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../coach_detail/coach_detail?id=' + id
    })
  },
  //画面数据格式预处理
  preProcessData: function () {
    var page = this;
    var sections = page.data.sections,
        coach_answer = page.data.coach_answer;
    sections.map((sec, s_index) => {
      sections[s_index].questions.map((q,q_index) => {
        coach_answer.item_list.map((ans) => {
          if (ans.uuid == q.uuid) {
            sections[s_index].questions[q_index].correct = q.correct;
            sections[s_index].questions[q_index].student_answer = ans.answer;
            sections[s_index].questions[q_index].if_right = ans.if_right;

            //多选题的情况,答案转数组
            if (q.category == 'select' && q.correct.length > 1) {
              sections[s_index].questions[q_index].correct = q.correct.split('');
              sections[s_index].questions[q_index].student_answer = ans.answer.split('');
              // sections[s_index].questions[q_index].if_right = ans.if_right;
            }

          //  单选题作答多个答案的情况
            if (q.category == 'select' && q.correct.length == 1 && q.student_answer.length > 1) {
              sections[s_index].questions[q_index].correct = q.correct.split('');
              sections[s_index].questions[q_index].student_answer = ans.answer.split('');
            }
          }
        })
      });
    });

    page.setData({
      sections: sections
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    });
  },
  toggleCatalog: function (e) {
    var page = this;
    var expand_status = e.currentTarget.dataset.expand;
    var id = e.currentTarget.dataset.id,
        sections = page.data.sections;

    sections.map((item,s_index) => {
      sections[s_index].questions.map((q,q_index) => {
        if (sections[s_index].questions[q_index].uuid == id) {
          sections[s_index].questions[q_index].expand = !expand_status;
        }
      })
    });

    page.setData({
      sections: sections
    });
  },
  //单选题处理
  onChange(e) {
    var page = this;

    //已提交的情况间接实现只读效果
    if (page.data.if_commit == 2) {
      return;
    }

  },
  //判断题处理
  onPDChange(e) {
    var page = this;

    //已提交的情况间接实现只读效果
    if (page.data.if_commit == 2) {
      return;
    }

  },
  //多选题处理
  onCBChange(e) {
    var page = this;

    //已提交的情况间接实现只读效果
    if (page.data.if_commit == 2) {
      return;
    }
  },
  doJudge: function (e) {
    var page = this,
        select_qid = e.currentTarget.dataset.id,
        if_right = e.currentTarget.dataset.ifright,
        sections = page.data.sections;

    sections.map((item, index) => {
      sections[index].questions.map((q, i) => {
        if (sections[index].questions[i].uuid == select_qid) {
          sections[index].questions[i].if_right = if_right;
        }
      })
    });
    page.setData({
      sections: sections
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var page = this;
    var coach_id = options.id == undefined ? 85 : options.id;
    page.setData({
      coach_id: coach_id
    })
    app.sendRequest({
      hideLoading: true,
      url:app.api.coach.coach_info,
      data: {coach_id:coach_id},
      success: coach_info_res => {
        app.setPageTitle(coach_info_res.data.name);
        app.sendRequest({
          hideLoading: true,
          url: page.data.downloadUrl + '/' + coach_info_res.data.question_url,
          success: res => {
            let all_coach_videos = coach_info_res.data.video_list;
            page.setData({
              // video_list: coach_info_res.data.video_list,
              coach_name: res.name,
              sections: res.sections,
              questionCount: res.questionCount
            })

            app.sendRequest({
              hideLoading: true,
              url: app.api.coach.coach_answer,
              data: {coach_id: coach_id},
              success: res => {
                console.log(res.data)
                var answer = res.data;
                if (answer != null && answer.finish != undefined) {
                  var ans_pic = answer.picture_list || [];
                  var item_list = answer.item_list || [];
                  var correct_num = 0,
                      total_num = item_list.length;
                  if (ans_pic.length > 0) {
                    ans_pic.map((p, i) => {
                      ans_pic[i] = page.data.downloadUrl + '/' + p
                    });
                  }
                  if (item_list.length > 0) {
                    item_list.map((p, i) => {
                      if (answer.item_list[i].if_right==1) {
                        correct_num++;
                      }
                    });
                  }
                  page.setData({
                    percent: Math.floor(correct_num / total_num * 100) + '%',
                    coach_answer: answer,
                    if_commit: 2,
                    files: ans_pic
                  })

                  page.preProcessData();
                  page.processHtml();
                  page.setData({
                    showSkeleton: false
                  });
                }


              }
            })

            app.sendRequest({
              hideLoading: true,
              url: app.api.coach.coach_correct_item,
              data: {coach_id: coach_id},
              success: res => {
                var video_data = res.data;
                var video_list_tmp = video_data.list || [];
                var video_list = all_coach_videos;
                video_list_tmp.map((v, k) => {
                  if (v.url != '') {
                    video_list.push(v)
                  }
                });
                page.setData({
                  video_list: video_list
                })
              }
            })
          }
        })

      }
    })



    // this.preProcessData();
    // this.processHtml();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that =this;
    //清除计时器  即清除setInter
    clearInterval(that.data.setInter)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})